﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace IceDog.Lib.IceDogSocket
{
    public class SimpleSocketServer
    {
        private string ip = "127.0.0.1";
        private int port = 8800;

        IPAddress address = null;
        Socket socket = null;

        public SimpleSocketServer()
        {

            address = IPAddress.Parse(ip);
            //step 1 实例化 socket 对象
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //step2 绑定ip地址和端口
            socket.Bind(new IPEndPoint(address, port));
            //step3 监听ip地址和端口
            socket.Listen(0);
            Console.WriteLine("服务端(" + ip + ":" + port + ")进入监听状态，等待客户端连接中。。。");

            var accept = socket.Accept();
            Console.WriteLine("有客户端连接，连接已经建立");

            this.ReceiveData();

            string sendStr = "来自服务端的消息：你好";
            byte[] sendByte = Encoding.UTF8.GetBytes(sendStr);
            accept.Send(sendByte, sendByte.Length, 0);
            accept.Close();
            Console.WriteLine("服务端accept socket关闭");
            socket.Close();
            Console.WriteLine("服务端socket关闭");
        }

        

        public void Send(byte[] byteData)
        {
            try
            {
                int blength = byteData.Length;
                var head = BitConverter.GetBytes(blength);
                var hlength = head.Length;
                var data = new byte[hlength + blength];
                Array.Copy(head, data, hlength);
                Array.Copy(byteData, 0, data, hlength, blength);
                this.socket.BeginSend(data, 0, data.Length, 0, (ar) =>
                {
                    var handler = ar.AsyncState as Socket;

                    handler.EndSend(ar);
                }, this.socket);
            }
            catch (Exception e)
            {
                throw;
            }
        }
        public void ReceiveData()
        {
            var buffer = new byte[4096];
            this.socket.BeginReceive(buffer, 0, buffer.Length, 0, ReceiveDataCallback, null);
        }

        public void ReceiveDataCallback(IAsyncResult ar)
        {
            var buffer = new byte[4096];
            try
            {
                int result = this.socket.EndReceive(ar);
                if (result > 0)
                {
                    byte[] data = new byte[result];
                    Array.Copy(buffer, 0, data, 0, result);
                    //在此次可以对data进行按需处理
                    string recStr = "";
                    recStr += Encoding.UTF8.GetString(data);
                    Console.WriteLine("服务端获得信息:{0}", recStr);
                    this.socket.BeginReceive(buffer, 0, buffer.Length, 0, ReceiveDataCallback, null);
                }
                else
                {
                    this.socket.Shutdown(SocketShutdown.Both);
                    this.socket.Close();
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }
    }
}
